﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using TripsLogic.controller;
using System.Data;
using TripsLogic.model;

namespace TripsLogic
{
    public partial class address : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!this.IsPostBack)
            {
                checkLogInStatus();
                loadLang();
                loadAddress();

            }
            ClientScript.RegisterStartupScript(Page.GetType(), "OnLoad", "autoinitialize();", true);
            this.Title = LangController.getLng("litAddressManager.Text", "Address Manager");
        }

        private void checkLogInStatus()
        {
            string restrictedPages = SysIniController.getSetting("Global_UserPages", "profile.aspx;change-password.aspx;trips.aspx;address.aspx");
            if (restrictedPages.Contains(System.IO.Path.GetFileName(Request.ServerVariables["SCRIPT_NAME"]).ToString()))
            {
                if (Session["Email"] == null || Session["Email"].ToString() == "")
                {
                    Session["RefUrl"] = HttpContext.Current.Request.Url.AbsoluteUri.Substring(0, HttpContext.Current.Request.Url.AbsoluteUri.LastIndexOf('/')) +
                        Request.RawUrl;
                    Response.Redirect("log-in", true);
                }
            }
        }

        private void loadAddress()
        {

            if (Session["UserId"] != null && Session["UserId"].ToString() != "")
            {
                DataTable dt = AddressController.getAddressByUserId(Session["UserId"].ToString());
                if (dt != null && dt.Rows.Count > 0)
                {
                    // TEN_DUONG SO_NHA, ZIP_CODE THANH_PHO, COUNTRY
                    dt.Columns.Add("FullAddress", typeof(string));
                    foreach (DataRow dr in dt.Rows)
                    {
                        string adr = dr["Address"].ToString();
                        if (dr["ZipCode"].ToString() != "")
                            adr += ", " + dr["ZipCode"].ToString();
                        if (dr["CITY"].ToString() != "")
                            adr += " " + dr["CITY"].ToString();
                        if (dr["Country"].ToString() != "")
                            adr += ", " + dr["Country"].ToString();
                        dr["FullAddress"] = adr;
                    }
                    dgrAddress.DataSource = dt;
                    dgrAddress.DataBind();
                }
            }
        }

        private void loadLang()
        {
            litAddress.Text = LangController.getLng("litAddress.Text", "Address");
            litAddressManager.Text = LangController.getLng("litAddressManager.Text", "Address Manager");
            litAddressManagerDesc.Text = LangMsgController.getLngMsg("litAddressManager.Desc", "Please use auto-complete feature to correctly fill in your addresses. Your valid address's format is '<font style='font-weight:bold'>STREETNAME HOUSENUMBER</font>, <font style='font-weight:bold'>ZIPCODE CITY</font>, <font style='font-weight:bold'>COUNTRY</font>'");

            lbtCancel.Text = LangController.getLng("litCancel.Text", "Cancel");
            lbtDeleteAddress.Text = LangController.getLng("litDelete.Text", "Delete");
            lbtSave.Text = LangController.getLng("litSave.Text", "Save");
            lbtAddAddress.Text = LangController.getLng("litAdd.Text", "Add");

            litAddEditAddress.Text = LangController.getLng("litAddEditAddress.Text", "Add / Edit an address");
            litAddEditAddressDesc.Text = LangMsgController.getLngMsg("litAddEditAddress.Desc", "Please type some chars to activate auto-complete address feature.");

            litAlias.Text = LangController.getLng("litAlias.text", "Alias");
        }

        protected void lbtSave_Click(object sender, EventArgs e)
        {
            bool rs;
            if (this.hdfId.Value != "")
            {
                rs = AddressController.updateAddress(new Address{
                    address = txtAddress.Text,
                    id = int.Parse(hdfId.Value),
                    alias = txtAlias.Text
                    
                });
            }
            else
            {
                rs = AddressController.createAddress(new Address{
                    address = txtAddress.Text,
                    userId = int.Parse(Session["UserId"].ToString()),
                    alias = txtAlias.Text
                });
            }
            if (rs)
            {
                // upload Image
                string id = this.hdfId.Value == "" ? AddressController.getCurrentId() : hdfId.Value;

                loadAddress();
                lblfrmResponse.ForeColor = System.Drawing.Color.Green;

                if (this.hdfId.Value == "")
                {
                    lblfrmResponse.Text = LangController.getLng("litAddOk.Text", "Added successfully");
                }
                else
                {
                    lblfrmResponse.Text = LangController.getLng("litUpdateOk.Text", "Updated successfully");
                }
                frmResponse.Visible = true;
            }
            else
            {
                lblfrmResponse.ForeColor = System.Drawing.Color.Red;
                if (this.hdfId.Value == "")
                {
                    lblfrmResponse.Text = LangController.getLng("litAddError.Text", "Add fail");
                }
                else
                {
                    lblfrmResponse.Text = LangController.getLng("litUpdateError.Text", "Update fail");
                }

                frmResponse.Visible = true;
            }
            resetAddAddress();
        }


        protected void lbtDeleteAddress_Click(object sender, EventArgs e)
        {
            string gvIDs = "(-1";
            bool chkBox = false;
            //'Navigate through each row in the GridView for checkbox items
            for (int i = 0; i < dgrAddress.Items.Count; i++)
            {
                CheckBox deleteChkBxItem = (CheckBox)dgrAddress.Items[i].FindControl("deleteRec");
                if (deleteChkBxItem.Checked)
                {
                    chkBox = true;
                    // Concatenate GridView items with comma for SQL Delete
                    gvIDs += "," + dgrAddress.Items[i].Cells[1].Text;
                    //delete images?

                }
            }
            gvIDs += ")";

            if (chkBox)
            {
                bool result = AddressController.deleteAddress(gvIDs);
                if (result)
                {
                    loadAddress();
                    //Delete images
                    try
                    {

                        lblfrmResponse.ForeColor = System.Drawing.Color.Green;
                        lblfrmResponse.Text = LangController.getLng("litDeleteOk.Text", "Deleted successfully");
                        frmResponse.Visible = true;
                    }
                    catch
                    {
                    }
                }
                else
                {
                    lblfrmResponse.ForeColor = System.Drawing.Color.Red;
                    lblfrmResponse.Text = LangController.getLng("litDeleteError.Text", "Delete fail");
                    frmResponse.Visible = true;
                }
            }
            resetAddAddress();
        }

        private void resetAddAddress()
        {
            txtAddress.Text = "";
            hdfId.Value = "";
            divAddDelete.Attributes["style"] = "display:block;padding-top:15px;";
            contactform.Attributes["style"] = "display:none;";
        }

        protected void dgrAddress_EditCommand(object source, DataGridCommandEventArgs e)
        {
            int iIndex = e.Item.DataSetIndex;
            loadAddress();
            DataTable dt = (DataTable)dgrAddress.DataSource;
            DataRow dr = dt.Rows[iIndex];

            this.txtAddress.Text = dr["Address"].ToString();
            this.hdfId.Value = dr["Id"].ToString();
            divAddDelete.Attributes["style"] = "display:none";
            contactform.Attributes["style"] = "display:block;padding-top:15px;";
            frmResponse.Visible = false;
        }

        protected void dgrAddress_PageIndexChanged(object source, DataGridPageChangedEventArgs e)
        {
            dgrAddress.CurrentPageIndex = e.NewPageIndex;
            loadAddress();
            frmResponse.Visible = false;
            resetAddAddress();
        }
    }
}